using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Media.Imaging;
using Legacy.Core.SaveGameManagement;

namespace MMXSaveGameConverter
{
    internal sealed class SavFileWriter : FileWriterBase
    {
        private readonly string _savPath;

        public SavFileWriter(SaveGameViewItem item)
            : base(item)
        {
            _savPath = Path.ChangeExtension(item.FullPath, ".sav");
        }

        public override void Write()
        {
            using (Stream output = File.Create(_savPath))
            {
                WriteSaveGame(output, Item.Name);
                WriteScreenshot(output);
            }
        }

        protected override void WriteScreenshot(Stream output)
        {
            long oldPosition = output.Position;
            output.WriteInt32(0);
            base.WriteScreenshot(output);
            long newPosition = output.Position;

            int length = (int)(newPosition - oldPosition - 4);
            output.Seek(oldPosition, SeekOrigin.Begin);
            output.WriteInt32(length);
            output.Seek(newPosition, SeekOrigin.Begin);
        }
    }
}